package com.phone580.app.setting;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.xml.sax.SAXException;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.Toast;

import com.phone580.app.CommonData;
import com.phone580.app.entity.UpdateEntity;
import com.phone580.app.model.CheckUpdateModel;
import com.phone580.app.net.HttpAccess;
import com.phone580.app.untilty.CommonUtility;

/**
 * 升级apk
 * @author matthew
 *
 */
public class UpdateTask extends AsyncTask<String, Integer, Integer> {
	private ProgressDialog mProgressDialog;
	private Context context;
	private static final String APK_VERSION = "apk_version";
	private static final int SUCCESS = 1;
	private static final int FAILD = 0;
	private static final int NO_NEW_VERSION = 2;
	private String version;
	String apkPath = CommonData.APP_PATH + "/phone580.apk";

	public UpdateTask(Context context) {
		this.context = context;
		version = CommonUtility.getStoreValue(context, APK_VERSION);
	}

	@Override
	protected void onPreExecute() {
		mProgressDialog = new ProgressDialog(context);
		mProgressDialog.setMessage("正在查询更新");
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDialog.setMax(100);
		mProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
						UpdateTask.this.cancel(true);
					}
				});
		mProgressDialog.show();
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		mProgressDialog.setMessage(values[0] + "");
		mProgressDialog.setProgress(values[0]);
	}

	@Override
	protected Integer doInBackground(String... params) {
		if (version == null || "".equals(version)) {
			version = "0";
		}
		String checkUpdateURL = "http://www.phone580.com:8082/websamp/pubapi/checkupdate?isPub=1&type=FBS_MOBILE_APK&versioncode="
				+ version;
		try {
			CheckUpdateModel model = new CheckUpdateModel();
			String result = HttpAccess.doGet(checkUpdateURL);
			UpdateEntity entity = model.parseCheckUpdateStep1(result.trim());
			if (entity != null) {
				//entity.getVersionCode().equals(version)
				if (true) {
					CommonUtility.storeValue(context, APK_VERSION,
							entity.getVersionCode());
					byte[] content = downloadXMLFile(entity.getUrlRoot()
							+ entity.getConfigFile());
					if (content.length != 0) {
						String xml = new String(content, "utf-8");
						xml = xml.substring(xml.indexOf("<"),
								xml.lastIndexOf(">") + 1);
						String name = model.parseCheckUpdateStep2(xml);
						if (name != null) {
							downloadDataFile(entity.getUrlRoot() + name,
									apkPath);
							return SUCCESS;
						}
					}
				} else {
					return NO_NEW_VERSION;
				}
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return FAILD;
	}

	private byte[] downloadXMLFile(String url) throws IOException {
		URL httpurl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) httpurl
				.openConnection();
		int size = connection.getContentLength();
		byte[] b = new byte[4096];
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int len = 0;
		InputStream in = connection.getInputStream();
		int t = 0;
		while ((len = in.read(b, 0, b.length)) != -1) {
			t += len;
			// Message msg = new Message();
			// msg.what = SplashActivity.DOWNLOAD_CONFIG_FLAG;
			// msg.arg1 = (int)((t / (float)size) * 100);
			// handler.sendEmptyMessage(SplashActivity.DOWNLOAD_CONFIG_FLAG);
			bos.write(b, 0, len);
		}
		connection.disconnect();
		byte[] data = bos.toByteArray();
		bos.close();
		return data;
	}

	private void downloadDataFile(String url, String path) throws IOException {
		URL httpurl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) httpurl
				.openConnection();
		int size = connection.getContentLength();
		byte[] b = new byte[10240];
		FileOutputStream fos = new FileOutputStream(path);
		int len = 0;
		InputStream in = connection.getInputStream();
		int t = 0;
		while ((len = in.read(b, 0, b.length)) != -1) {
			t += len;
			// Message msg = new Message();
			// msg.what = SplashActivity.DOWNLOAD_DATA_FLAG;
			// msg.arg1 = (int)((t / (float)size) * 100);
			// handler.sendMessage(msg);
			publishProgress((int) ((t / (float) size) * 100));
			fos.write(b, 0, len);
		}
		fos.close();
		connection.disconnect();
	}

	@Override
	protected void onPostExecute(Integer result) {
		mProgressDialog.dismiss();
		if (result == NO_NEW_VERSION) {
			Toast.makeText(context, "没有可用更新", Toast.LENGTH_SHORT).show();
		}
		if (result == SUCCESS) {
//			Toast.makeText(context, "更新成功", Toast.LENGTH_SHORT).show();
		    Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(apkPath)),
                            "application/vnd.android.package-archive");
            context.startActivity(intent);
		}
		if (result == FAILD) {
			Toast.makeText(context, "更新失败", Toast.LENGTH_SHORT).show();
		}
	}

}
